<template>
  <div>
    <div class="login">
      <h2>登录</h2>
      <Divider></Divider>
      <Form ref="login" :model="loginData" :rules="validLogin" @keyup.enter.native="login('login')">
        <FormItem prop="username">
          <Input type="text" v-model.trim="loginData.username" placeholder="用户名">
            <Icon type="ios-person-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem prop="password">
          <Input type="password" v-model.trim="loginData.password" placeholder="密码">
            <Icon type="ios-lock-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem prop="password">
          <Input type="text" v-model.trim="loginData.imageCode" placeholder="验证码">
            <Icon type="ios-create-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem style="margin-bottom: 5px">
          <div class="imageCode" @click="changeImgCode">
            <img style="height: 28px" :src="imageCode" alt="imageCode"/>
          </div>
        </FormItem>
        <FormItem style="margin-top: 10px">
          <div style="margin-bottom: 10px">
            <Checkbox v-model="loginData.remember" label="记住我">记住我</Checkbox>
          </div>
          <Button style="width: 316px" @click="login('login')" class="login-form-button" type="primary">
            登录
          </Button>
          <div style="margin-top: 20px">
            <a @click="toRegister">
              注册用户
            </a>
            <a @click="toUpdatePassword" style="margin-left: 40px">
              忘记密码
            </a>
          </div>
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script>
  import axios from "axios";
  import {mapActions} from "vuex"

  export default {
    name: "Login",
    data() {
      return {
        loginData: {
          username: '',
          password: '',
          imageCode: '',
          remember: true
        },
        validLogin: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {type: 'string', min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
          ],
          imageCode: [
            {required: true, message: '请输入验证码', trigger: 'blur'}
          ]
        },
        imageCode: ''
      }
    },
    mounted() {
      this.changeImgCode();
    },
    methods: {
      ...mapActions(['setUser']),
      login(name) {
        const loginData = this.loginData;
        this.$refs[name].validate((valid) => {
          if (valid) {
            let params = new URLSearchParams();
            params.append("username", loginData.username);
            params.append("password", loginData.password);
            params.append("imageCode", loginData.imageCode);
            params.append("remember-me", loginData.remember);

            // 加载中
            this.$Spin.show({
              render: (h) => {
                return h('div', [
                  h('Icon', {
                    'class': 'demo-spin-icon-load',
                    props: {
                      type: 'ios-loading',
                      size: 18
                    }
                  }),
                  h('div', LOADING)
                ])
              }
            });

            const url = LOGIN_API;
            axios.post(url, params).then(response => {
              this.$Spin.hide();
              const data = response.data;
              if (data.code === -2) {
                // 设置当前登录用户的信息
                this.setUser();
                this.$router.push('/');
              } else if (data.code === -3) {
                this.changeImgCode();
                this.$Message.error(data.data.message);
              } else {
                this.changeImgCode();
                this.$Message.error(data.msg);
              }
            }).catch(error => {
              // 登录失败
              this.$Spin.hide();
              console.log(error);
              this.$Message.error(ERROR_MSG);
              this.changeImgCode();
            })
          }
        })
      },
      changeImgCode() {
        const url = IMAGE_CODE_API;
        axios.get(url).then(response => {
          const data = response.data;
          if (data.code === 1) {
            this.imageCode = 'data:image/png;base64,' + data.data.imageCode;
          }
        }).catch(error => {
          console.log(error);
        });
      },
      toRegister() {
        this.$router.push("/register");
      },
      toUpdatePassword() {
        this.$router.push("/updatePassword");
      }
    }
  }
</script>

<style scoped>
  .login {
    width: 400px;
    height: 460px;
    border: #cccccc 1px solid;
    margin: 100px auto;
    border-radius: 20px;
    text-align: center;
    padding: 20px 40px;
    background-color: #fbfbfb;
  }

  #components-form-demo-normal-login .login-form-button {
    width: 100%;
  }

  .imageCode {
    height: 30px;
    width: 316px;
    border: 1px solid #dcdee2;
    border-radius: 4px;
    cursor: pointer;
  }

  .demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }
</style>
